<template>
  <div class="profile-container">
    <div class="user-info">
      <div class="avatar">
        <el-avatar :size="80" :src="avatar" />
      </div>
      <div class="info">
        <h3>{{ userInfo.userName || '未设置昵称' }}</h3>
        <p>{{ userInfo.wechatId ? `微信号: ${userInfo.wechatId}` : '' }}</p>
        <p v-if="userInfo.balance !== undefined">余额: ¥{{ userInfo.balance.toFixed(2) }}</p>
      </div>
    </div>

    <div class="menu-list">
      <el-card shadow="hover" class="menu-item" @click="goToAddressList">
        <div class="menu-content">
          <el-icon><Location /></el-icon>
          <span>收货地址</span>
        </div>
      </el-card>

      <el-card shadow="hover" class="menu-item" @click="handleLogout">
        <div class="menu-content">
          <el-icon><SwitchButton /></el-icon>
          <span>退出登录</span>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import {
  Location,
  SwitchButton
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const router = useRouter();
const avatar = ref('/src/static/image/header/wjt.png')
const userInfo = ref({
  userName: '',
  wechatId: '',
  balance: 0
});

// 服务降级标志
const isServiceDegraded = ref(false);

// 从本地存储获取用户信息
const getLocalUserInfo = () => {
  const wechatId = localStorage.getItem('wechat_id');
  const nickname = localStorage.getItem('nickname') || '';
  const localAvatar = localStorage.getItem('avatar') || '';

  return {
    userName: nickname,
    wechatId: wechatId || '',
    avatar: localAvatar,
    balance: 0
  };
};

// 检查API是否可用
// const checkApiAvailability = async () => {
//   try {
//     const response = await fetch('http://localhost:8080/health', {
//       method: 'GET',
//       headers: {
//         'Content-Type': 'application/json'
//       }
//     });
//     return response.ok;
//   } catch (error) {
//     return false;
//   }
// };

// 带重试机制的API请求
const fetchWithRetry = async (url, options, retries = 2) => {
  try {
    const response = await fetch(url, options);
    if (!response.ok) throw new Error('API request failed');
    return await response.json();
  } catch (error) {
    if (retries > 0) {
      await new Promise(resolve => setTimeout(resolve, 1000));
      return fetchWithRetry(url, options, retries - 1);
    }
    throw error;
  }
};

const fetchUserInfo = async () => {
  const wechatId = localStorage.getItem('wechat_id');
  const token = localStorage.getItem('access_token');

  if (!wechatId || !token) {
    ElMessage.error('用户信息缺失');
    return;
  }

  try {

    const data = await fetchWithRetry(
        `http://localhost:8080/user/by-wechat/${wechatId}`,
        {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        }
    );

    userInfo.value = {
      userName: data.userName || '',
      wechatId: data.wechatId || wechatId,
      avatar: localStorage.getItem('avatar') || '',
      balance: data.balance || 0
    };

    // 更新本地存储
    if (data.userName) {
      localStorage.setItem('nickname', data.userName);
    }

    // 重置降级标志
    isServiceDegraded.value = false;
  } catch (error) {
    console.error('Error fetching user info:', error);
    isServiceDegraded.value = true;

    // 使用本地存储的数据作为降级方案
    userInfo.value = getLocalUserInfo();

    // 显示降级通知
    ElMessage.warning('网络不稳定，显示本地缓存信息');
  }
};

const goToAddressList = () => {
  if (isServiceDegraded.value) {
    ElMessage.warning('当前网络不稳定，部分功能可能受限');
  }
  router.push('/address-list');
};

const handleLogout = () => {
  localStorage.removeItem('access_token');
  localStorage.removeItem('wechat_id');
  localStorage.removeItem('nickname');
  localStorage.removeItem('avatar');
  ElMessage.success('已退出登录');
  router.push('/login');
};

onMounted(() => {
  const token = localStorage.getItem('access_token');
  if (!token) {
    ElMessage.error('请先登录');
    router.push('/login');
  } else {
    fetchUserInfo();
  }
});
</script>

<style scoped>
.profile-container {
  padding: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.avatar {
  margin-right: 20px;
}

.info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
}

.info p {
  margin: 0 0 4px 0;
  color: #666;
  font-size: 14px;
}

.menu-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.menu-item {
  cursor: pointer;
}

.menu-content {
  display: flex;
  align-items: center;
}

.menu-content .el-icon {
  margin-right: 12px;
  font-size: 18px;
  color: #666;
}

.menu-content span {
  font-size: 16px;
}
</style>